<?php

class Excelfile_Controller Extends Controller {

    private $objectlist;

    function _init() {
        check_level(50, segment(0), segment(1, 'index'));
        //header("Content-type:text/html;charset=UTF-8"); 
        //date_default_timezone_set('PRC'); 
        $this->objectlist = get_type_object_id_name();
        //$this->objectlist = get_type_object_db();
    }

    function index() {
        $this->view->display("mail/excelfile/index");
    }

    function flexigrid() {
        //读取flexigrid传输的数据
        list($colkey, $colsinfo, $where, $sortname, $sortorder, $offset, $rp, $page) = $this->common->get_flexigrid_params();
        $path=MULTIUPLOADPATH.'excel/mail/';
        $filearray=get_filenamesbydir($path,2);
        $total=count($filearray);
        for ($i=$offset;$i<$total;$i++) {
            $n['type']      = '群发单邮件';
            $n['intime']    =date('Y-m-d H:i:s',$filearray[$i]['time']);
            $n['filename']  =$filearray[$i]['filename'];
            $rows[] = array('id' => $n['filename'], 'cell' => ($n));
        }
        
        $result = array(
            'page' => $page,
            'total' => $total,
            'rows' => $rows
        );
        echo json_encode($result);
    }
    
    function add() {
    	set_time_limit(0);
    	if(is_submit())
    	{
    		//print_r($_FILES);
    		if($_FILES['file']['error']>0)
    		{
    			echo "Error: " . $_FILES["file"]["error"] . "<br />";
    			//return;
    		}

    		$filetype   =$_FILES['file']['type'];
    		$tmp_name   =$_FILES['file']['tmp_name'];	//临时文件名
    		$file_name  =$_FILES['file']['name'];	//文件名
    		$awardpath       =MULTIUPLOADPATH.'excel/mail/'.$file_name;
    			
    		//判断下后缀是否正确
    		//echo " filename=$file_name ";
    		$exfile = substr(strrchr($file_name, '.'), 1);
    		//echo " exfile1 = $exfile ";
    		
    		$exfile = strtolower(trim($exfile));
    		//echo " exfile2 = $exfile ";
    		
    		if ( 'xls' != $exfile && 'xlsx' != $exfile)
    		{
    			echo " error file should be xls or xlsx ";
    			return;
    		}
    		
    		//先判断下此文件存在 否？
    		if(file_exists($awardpath))
    		{
    			//unlink($awardpath);
    			echo " error plz input another name $file_name ";
    			return;
    		}
    		
    		//上传文件
    		$ret = move_uploaded_file($tmp_name, $awardpath);
    		if(true != $ret)
    		{
    			echo " error fail to upload file";
    			return;
    		}

    		$err = "";	//错误信息集
			//$this->load->database("db");
			$this->db->select_db();
    		$area_host  =  get_area_list_url();
    		$excelarray =  readExcel($awardpath);
    		//echo " nwefilename = $newfilename ";
    		//var_dump($excelarray);
    		//要发送的数据
    		$senddata = array();
    		
    		//i=2表示从第二行开始，第一行是标题栏
    		for($i=2;$i<=count($excelarray);$i++)
    		{
    			$awardarray['areanum']            =$excelarray[$i]['A'];	//区号
    			$awardarray['reciver_name']       =$excelarray[$i]['B'];	//角色名
    			$awardarray['receiver_id']         =$excelarray[$i]['C'];	//角色id
    			$awardarray['mail_title']      	  =$excelarray[$i]['D'];	//邮件标题
    			$awardarray['mail_content']      =$excelarray[$i]['E']; 	//邮件正文
    			$awardarray['keep_time']      	=$excelarray[$i]['F'];		//保存时间
    			
    			//第一个物品
    			$awardarray['item0'] = $excelarray[$i]['G'];
    			$awardarray['amount0'] = $excelarray[$i]['H'];
    			$awardarray['equiplv0'] = $excelarray[$i]['I'];
    			
    			//第二个物品
    			$awardarray['item1'] = $excelarray[$i]['J'];
    			$awardarray['amount1'] = $excelarray[$i]['K'];
    			$awardarray['equiplv1'] = $excelarray[$i]['L'];
    			
    			//第三个物品
    			$awardarray['item2'] = $excelarray[$i]['M'];
    			$awardarray['amount2'] = $excelarray[$i]['N'];
    			$awardarray['equiplv2'] = $excelarray[$i]['O'];
    			
    			//第四个物品
    			$awardarray['item3'] = $excelarray[$i]['P'];
    			$awardarray['amount3'] = $excelarray[$i]['Q'];
    			$awardarray['equiplv3'] = $excelarray[$i]['R'];

    			//print_r($awardarray);
    			//数据有效性验证,只要一个写错了，就不让发。。。
    			$ret = $this->validData($awardarray);
    			if('success' != $ret)
    			{
    				echo " pos: $i".$ret;
    				//删除下此文件
    				unlink($awardpath);
    				return; 
    			}   			
    			//print_r($awardarray);
    			
    			$senddata[] = $awardarray;
 
    		}
    		
    		//记下日志
    		insert_log(translate('MENU_MAIL_EXCELFILE'),translate('ADD'), null,$awardpath);
    		
    		//var_dump($senddata);
    		//以上数据没有错误，就一条条的来发了
    		foreach ($senddata as $value)
    		{
    			$areanum = $value['areanum'];
    			unset($value['areanum']);	//发送数据时，把此字段去掉
    			
	    		$url = $area_host[$areanum]. array_to_stringparam($value)."action=15";
	    		//echo " url=$url ";
	    		
	    		$ret=  vpost($url);
	    		//echo " ret = $ret url = $url";
	    		
	    		if (FALSE===ret)
	    		{
	    			$err .=" error column:".$i." name:".$value['name']." ";
	    		}
	    		
	    		//print_r($value);
	    		//把空字符去掉
	    		foreach ($value as $k=>$v)
	    		{
	    			if("" == $v)
	    			{
	    				unset($value[$k]);
	    			}
	    		}
	    		//print_r($value);
	    		
	    		
	    		//增加两个额外的数据
    			$value['insert_time']      =time();	//当前时间
    			$value['mailtype']      =0;	//0表示单发邮件
    			
    			$value['areanum'] = $areanum;	//插入到记录中时，把此字段加上来
	    		$value['issuccess'] = $ret==""? 3:$ret;	//若是空，就把此标记为未知的错误(3表示未知错误 )
	    		$this->db->insert("mail_sendlog",$value);
	    		
    		}
    		
    		if (empty($err))
    		{
    			$result = " success";
    		}
    		else
    		{
    			$result=" error:".$err;
    		}
    		echo "$result";
    		echo "<script>alert('".$result."');</script>";

    	}else
    	{
    		$this->view->display("mail/excelfile/add");
    	}
    }

    //根据物品名字或是objectid返回 物品的id
    /*
     * 成功返回objectid
     * 失败返回 -1
     */
    function getObjectIdByNameOrId($obj)
    {
    	$result = -1;	//默认失败
    	
    	$obj = trim($obj);	//去掉空格
    	
    	if(is_numeric($obj))
    	{
    		if($this->objectlist[$obj])
    		{
    			$result = $obj;
    		}
    	}else 
    	{
    		foreach ($this->objectlist as $key=>$value)
    		{
    			if($obj==$value)
    			{
    				$result = $key;
    				break;
    			}
    		}
    	}
    	return $result;
    }
    
    /*
     * 判断传入的数量是否正确
     * 正确返回相应的数量
     * 不正确返回-1
     */
    function getNumber($obj)
    {
    	$result = -1;
    	$obj = trim($obj);	//去掉空格
    	
    	if(is_numeric($obj))
    	{
    		if ($obj > 0) {
    			$result = $obj;
    		}
    	}
    	return $result;
    }
    
    function send($id = 0) {
        //echo ("asdfasfdasdf");
        //exit;
        set_time_limit(0);

        $rowdata = $this->db->one("SELECT * FROM mail_message WHERE autoid=$id");

        $areaIds = explode(",", $rowdata['area_host']); //需要推送的服务器ID数组
        //组织附件url字符串
        $i = 0;
        while ($i <= 4) {
            $typeid_num_arr = explode(",", $rowdata['item' . $i]);
            if (count($typeid_num_arr) !== 2) {//没有TypeID和数量两个数据 无效
                $i++;
                continue;
            }
            $str_items .= "item$i=" . $typeid_num_arr[0] . "&amount$i=" . $typeid_num_arr[1] . "&";
            $i++;
        }
        unset($rowdata['item'], $rowdata['amount']);


        $errorResultS = array();
        $str = array_to_stringparam($rowdata);
        if (in_array('0', $areaIds)) {
            $liveAreas = get_area_list_live();
            foreach ($liveAreas as $k => $v) {
                $strS = $v['host'] . $str . $str_items . "action=16";
                $strResultStr = vpost($strS);
                if ($strResultStr != '0' || $strResultStr === FALSE) {
                    $errorResultS[] = $v["name"];
                }
            }
        } else {
            $area_host = get_area_list_detal();
            foreach ($areaIds as $k => $v) {
                $strS = $area_host[$v]["host"] . $str . $str_items . "action=16";
                $strResultStr = vpost($strS);
                if ($strResultStr != '0' || $strResultStr === FALSE) {
                    $errorResultS[] = $area_host[$v]["name"];
                }
            }
        }

        //操作失败或者连接失败
        if (count($errorResultS) > 0) {
            $string = implode('、', $errorResultS) . " 发送失败！";
            echo $string;
        }
    }

    function edit($id = 0) {
        set_time_limit(0);
        $excelpath  =  MULTIUPLOADPATH.'excel/mail/'.$id;      
        $excelarray =  readExcel($excelpath);
        for($i=1;$i<=count($excelarray);$i++)
        {
            if($i==1)
            {
                $string="<tr bgcolor='#cccfff'>
                            <th width='60px'>{$excelarray[$i]['A']}</th>
                            <th>{$excelarray[$i]['B']}</th>
                            <th>{$excelarray[$i]['C']}</th>
                            <th>{$excelarray[$i]['D']}</th>
                            <th>{$excelarray[$i]['E']}</th>
                            <th>{$excelarray[$i]['F']}</th>
                            <th>{$excelarray[$i]['G']}</th>
                            <th>{$excelarray[$i]['H']}</th>
                         </tr>";
            }
            else 
           {
               $string.="<tr bgcolor='#ffffff'>
                            <td>{$excelarray[$i]['A']}</td>
                            <td>{$excelarray[$i]['B']}</td>
                            <td>{$excelarray[$i]['C']}</td>
                            <td>{$excelarray[$i]['D']}</td>
                            <td>{$excelarray[$i]['E']}</td>
                            <td>{$excelarray[$i]['F']}</td>
                            <td>{$excelarray[$i]['G']}</td>
                            <td>{$excelarray[$i]['H']}</td>
                         </tr>";
           }
        }
        $this->view->assign('string',$string);
        $this->view->display("mail/excelfile/edit");
    }

    //文件上传，暂时没有使用到
    function upload()
    {
    	//print_r($_FILES);
    	 
    	$filetype   =$_FILES['file']['type'];


    	$tmp_name   =$_FILES['file']['tmp_name'];
    	$file_name  =$_FILES['file']['name'];
    	$awardpath       =MULTIUPLOADPATH.'excel/mail/'.$file_name;
    	if(file_exists($awardpath))
    	{
    		unlink($awardpath);
    	}
    	$ret = move_uploaded_file($tmp_name, $awardpath);
    	echo " ret = $ret tmp_name:$tmp_name awardpath:$awardpath ";
    	$newfilename=MULTIUPLOADPATH.'excel/mail/mail'.date('YmdHis',time()).'.xlsx';
    	//$_SESSION['multiroleaward']=$newfilename;
    	$renameresult=rename($awardpath, $newfilename);
    	echo " renameresult:$renameresult awardpath:$awardarray newfilename:$newfilename ";
    	if($renameresult)
    	{
    		//$message='upload file success,Sending award……';
    		//echo "<script>alert('".$message."');</script>";
    		$type_object=$this->type_object();
    		$area_host  =  get_area_list_url();
    		$excelarray =  readExcel($newfilename);
    		for($i=2;$i<=count($excelarray);$i++)
    		{
    			$area_url                                  =$area_host[$excelarray[$i]['A']];
    			$awardarray[$area_url][0]['area_url']      =$area_url;
    			$awardarray[$area_url][$i]['name']         =$excelarray[$i]['B'];
    			$awardarray[$area_url][$i]['subject']      =$excelarray[$i]['C'];
    			$awardarray[$area_url][$i]['content']      =$excelarray[$i]['D'];
    			$item0                                     =  explode(':', $excelarray[$i]['E']);
    			$item1                                     =  explode(':', $excelarray[$i]['F']);
    			$item2                                     =  explode(':', $excelarray[$i]['G']);
    			$item3                                     =  explode(':', $excelarray[$i]['H']);
    			$awardarray[$area_url][$i]['item1']        =$type_object[$item0[0]];
    			$awardarray[$area_url][$i]['num1']         =(int)$item0[1];
    			$awardarray[$area_url][$i]['item2']        =$type_object[$item1[0]];
    			$awardarray[$area_url][$i]['num2']         =(int)$item1[1];
    			$awardarray[$area_url][$i]['item3']        =$type_object[$item2[0]];
    			$awardarray[$area_url][$i]['num3']         =(int)$item2[1];
    			$awardarray[$area_url][$i]['item4']        =$type_object[$item3[0]];
    			$awardarray[$area_url][$i]['num4']         =(int)$item3[1];
    		}
    		unset($excelarray);
    		unset($area_host);
    		$awardarray=  array_values($awardarray);
    		$area_host=  get_area_list_host();
    		$errorStr='';
    		for($j=0;$j<count($awardarray);$j++)
    		{
    			$area_url=$awardarray[$j][0]['area_url'];
    			unset($awardarray[$j][0]);
    			unset($jsonarray);
    			$jsonarray=array_values($awardarray[$j]);
    			$json=json_encode($jsonarray);
    			$url=$area_url.'json_str='.$json.'&is_same_content=0'.$_POST['is_same_content'].'&action=42';
    			$strResult[$area_url]=  vpost($url);
    			if ($strResult[$area_url] === FALSE)
    			$errorStr .= $area_host[$area_url] . translate('C_TIPS_ERROR_TEXT') . "\r\n";
    		}
    		unset($awardarray);
    		if (empty($errorStr))
    		$result = "success";
    		else
    		$result=$errorStr;
    		echo "<script>alert('".$result."');</script>";
    	}
    	else {
    		$message='fail upload file';
    		echo "<script>alert('".$message."');</script>";
    	}

    }
    
    function del($filename)
    {
    	$c = 0;
		$r = '';
    	
    	$path=MULTIUPLOADPATH.'excel/mail/';
    	$filefulpath = $path.$filename;
    	//echo " filefulpath:".$filefulpath;
    	if (unlink($filefulpath)) {
    		$c = 1;
    		$r = 'delete success';
    		insert_log(translate('MENU_MAIL_EXCELFILE'),translate('DEL'), array('filename'=>$filename));
    	}else 
    	{
    		$r = 'delete fail';
    	}
    	json_output($c, $r);
    }
    
	function multi() {
		//print_r($_POST);
		 $type = $this->input->post("type");
		 $ids = $this->input->post("ids");
		 $c = 0;
		 $r = '';
		 //echo " type = $type ";
		 //echo " ids = $ids ";
		 if (count(explode(',', $ids)) == 0) {
		 	$r = translate('C_INVALID_PARAMS');
		 } else 
		 {
			 if ($type == 'delete') {
			 	
			 	$path=MULTIUPLOADPATH.'excel/mail/';
		    	
		    	//echo " filefulpath:".$filefulpath;
			 	
			 	$files = explode(',', $ids);
			 	
			 	foreach ($files as $value)
			 	{
			 		$filefulpath = $path.$value;
			 		
			 		//echo " filefulpath ".$filefulpath;
			 		
			 		unlink($filefulpath);
			 	}
			 	insert_log(translate('MENU_MAIL_EXCELFILE'),translate('MULTI_DEL'), array('files'=>$files));
				$c = 1;
			 } else 
			 {
			 	$r = translate('C_INVALID_PARAMS');
			 }
		 }
		 json_output($c, $r);
		 
	}
    
	//验证数据是否是正确,在此需要传引用
	/*
	 *验证成功返回success
	 *其它都是错误 的 
	 */
	function validData(&$data)
	{
		$res = 'success';
		
		//print_r($data);
		
		for($i =0; $i < 1; ++$i)
		{
			if(!is_numeric($data['areanum']))
			{
				$res = "A areanum should be number ";
				break;
			}
			if (0 >= $data['areanum'] ) {
				$res = "A areanum should be big than 0 ";
				break;
			}
			//echo " name: $data[reciver_name] id: $data[reciver_id] ";
			//角色名与角色id至少要写一个
			if (""==$data['reciver_name'] && ""==$data['reciver_id']) {
				$res = " B or C reciver_name or reciver_id should not be null ";
				break;
			}
			
			//角色id要为数字 
			if(""!=$data['reciver_id'] && !is_numeric($data['reciver_id']))
			{
				$res = "C reciver_id should be number ";
				break;
			}
			if ( ""!=$data['reciver_id'] && 0 >= $data['reciver_id'] ) {
				$res = "C reciver_id should be big than 0 ";
				break;
			}

			//标题与正文不能为空
			if (""==$data['mail_title'] ) {
				$res = "D mail_title should not be null ";
				break;
			}
			
			if (""==$data['mail_content'] ) {
				$res = "E mail_content should not be null ";
				break;
			}
			
			//保存时间，需要大于等于1
			if(!is_numeric($data['keep_time']))
			{
				$res = "F keep_time should be number ";
				break;
			}
			if (0 >= $data['keep_time'] ) {
				$res = "F keep_time should be big than 0 ";
				break;
			}

			//第一个物品
			//全部都为空，就直接跳到下一行去
			if (""==$data['item0'] && ""==$data['amount0'] && ""==$data['equiplv0']) {
				continue;
			}
			//物品名称是否正确
			if ("" == $data['item0'] ) {
				$res = "G item0 should not be null  ";
				break;
			}
			$objectid = $this->getObjectIdByNameOrId($data['item0']);
			if(-1 == $objectid)
			{
				$res = "G can not find object id or name ";
				break;
			}else 
			{
				$data['item0'] = $objectid;
			}
			
			//数量是否正确
			if ("" == $data['amount0'] || !is_numeric($data['amount0']) ) {
				$res = "H amount0 should not be null or need be number ";
				break;
			}
			else if ( 0 > $data['amount0'] ) {
				$res = "H amount0 should be big then 0 ";
				break;
			}
			//var_dump($data['equiplv0']);
			//锻造等级是否正确		
			/*if ("" == $data['equiplv0'] ) 
			{
				$res = "I equiplv0 should not be null or need be number ";
				break;
			}else */
			if( !is_numeric($data['equiplv0']) ) 
			{
				$res = "I equiplv0  need be number ";
				break;
			}
			else if ( 0 > $data['equiplv0'] ) {
				$res = "I equiplv0 should be big then 0 ";
				break;
			}
			 
			//第二个物品 
			//全部都为空，就直接跳到下一行去
			if (""==$data['item1'] && ""==$data['amount1'] && ""==$data['equiplv1']) {
				continue;
			}
			//物品名称是否正确
			if ("" == $data['item1'] ) {
				$res = "J item1 should not be null  ";
				break;
			}

			$objectid = $this->getObjectIdByNameOrId($data['item1']);
			if(-1 == $objectid)
			{
				$res = "J can not find object id or name ";
				break;
			}else 
			{
				$data['item1'] = $objectid;
			}
				
			//数量是否正确
			if ("" == $data['amount1'] || !is_numeric($data['amount1']) ) {
				$res = "K amount1 should not be null or need be number ";
				break;
			}
			else if ( 0 > $data['amount1'] ) {
				$res = "K amount1 should be big then 0 ";
				break;
			}
				
			//锻造等级是否正确
			if ( !is_numeric($data['equiplv1']) ) {
				$res = "L equiplv1 need be number ";
				break;
			}
			else if ( 0 > $data['equiplv1'] ) {
				$res = "L equiplv1 should be big then 0 ";
				break;
			}
			
			//第三个物品 
			//全部都为空，就直接跳到下一行去
			if (""==$data['item2'] && ""==$data['amount2'] && ""==$data['equiplv2']) {
				continue;
			}
			//物品名称是否正确
			if ("" == $data['item2'] ) {
				$res = "M item2 should not be null  ";
				break;
			}
			
			$objectid = $this->getObjectIdByNameOrId($data['item2']);
			if(-1 == $objectid)
			{
				$res = "M can not find object id or name ";
				break;
			}else 
			{
				$data['item2'] = $objectid;
			}
			
			//数量是否正确
			if ("" == $data['amount2'] || !is_numeric($data['amount2']) ) {
				$res = "N amount2 should not be null or need be number ";
				break;
			}
			else if ( 0 > $data['amount2'] ) {
				$res = "N amount2 should be big then 0 ";
				break;
			}
			
			//锻造等级是否正确
			if ( !is_numeric($data['equiplv2']) ) {
				$res = "O equiplv2  need be number ";
				break;
			}
			else if ( 0 > $data['equiplv2'] ) {
				$res = "O equiplv2 should be big then 0 ";
				break;
			}
			
			//第四个物品
			//全部都为空，就直接跳到下一行去
			if (""==$data['item3'] && ""==$data['amount3'] && ""==$data['equiplv3']) {
				continue;
			}
			//物品名称是否正确
			if ("" == $data['item3'] ) {
				$res = "P item3 should not be null  ";
				break;
			}
				
			$objectid = $this->getObjectIdByNameOrId($data['item3']);
			if(-1 == $objectid)
			{
				$res = "P can not find object id or name ";
				break;
			}else 
			{
				$data['item3'] = $objectid;
			}
				
			//数量是否正确
			if ("" == $data['amount3'] || !is_numeric($data['amount3']) ) {
				$res = "Q amount3 should not be null or need be number ";
				break;
			}
			else if ( 0 > $data['amount3'] ) {
				$res = "Q amount3 should be big then 0 ";
				break;
			}
				
			//锻造等级是否正确
			if ( !is_numeric($data['equiplv3']) ) {
				$res = "R equiplv3 need be number ";
				break;
			}
			else if ( 0 > $data['equiplv3'] ) {
				$res = "R equiplv3 should be big then 0 ";
				break;
			}
		}
		return $res;
	}
}

?>